package jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * jdbc工具类
 */
public class JDBCUtil {

    //类加载时初始化连接池
    private static DataSource dataSource=null;
    static {
        Properties properties = new Properties();
        try {
            //加载配置文件./表示当前项目下
            properties.load(new FileInputStream("./src/main/resources/db.properties"));
            //看一下能不能获取到数据
//            System.out.println(properties.getProperty("user"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取链接
     * @return
     */
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭链接,关闭连接时将连接清洗干净放回连接池
     * @param connection
     */
    public static void closeConnection(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        try {
            if (connection!=null)
                connection.close();
            if (preparedStatement!=null)
                preparedStatement.close();
            if (resultSet!=null)
                resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
